﻿using AutoMapper;
using Ezpay.ServiceContract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ezpay.UI
{
    class EzpayService : IEzpayService
    {
        public CreateNewCustomerResponse CreateNewCustomer(CreateNewCustomerRequest request)
        {
            Thread.Sleep(2000);

            var customer = Mapper.Map<Customer>(request);
            GlobalDB.AddCustomer(customer);

            return new CreateNewCustomerResponse()
            {
                CustomerID = customer.CustomerID
            };
        }


        public UpdateCustomerResponse UpdateCustomer(UpdateCustomerRequest request)
        {
            Thread.Sleep(2000);

            var customer = GlobalDB.GetCustomer(request.CustomerID);

            Mapper.Map(request, customer);

            return new UpdateCustomerResponse();
        }


        public SearchResponse Search(SearchRequest request)
        {
            var searchText = request.Query;
            var response = new SearchResponse();

            var customers = new SearchResultGroup()
            {
                GroupName = "Customer",
                Items = (from customer in GlobalDB.Customers
                         where customer.FullName.IndexOf(searchText, StringComparison.InvariantCultureIgnoreCase) > -1
                         select new SearchResult()
                         {
                             Identifier = customer.CustomerID,
                             Description = customer.FullName
                         }).ToArray()
            };
            var agencies = new SearchResultGroup()
            {
                GroupName = "HousingAgency",
                Items = (from agency in GlobalDB.HousingAgencies
                         where agency.IndexOf(searchText, StringComparison.InvariantCultureIgnoreCase) > -1
                         select new SearchResult()
                         {
                             Identifier = agency,
                             Description = agency
                         }).ToArray()
            };

            response.Results = new[] { customers, agencies };

            return response;
        }


        public GetCustomerResponse GetCustomer(GetCustomerRequest request)
        {
            var customer = GlobalDB.GetCustomer(request.CustomerID);

            return Mapper.Map<GetCustomerResponse>(customer);
        }
    }
}
